extends CharacterBody2D

# 默认怪物行进速度
@export var speed : float = 100.0
# 用户实例
@export var player_reference : CharacterBody2D
# 怪物朝向
@export var direction : Vector2
# 伤害弹框
var damage_popup_node = preload("res://Scenes/Damage.tscn");
# 掉落物
var drop = preload("res://Scenes/Pickups.tscn")
# 存放距离角色最近的小怪与角色的距离
var separation : float
# 击退
var knockback :  Vector2
# 对玩家造成的伤害
var damage : float

var health : float:
	set(value):
		health = value
		if health <= 0:
			# 死亡掉落
			drop_item()
			# 死亡时移除怪物(自己)对象
			queue_free()

# 精英标记
var elite : bool = false:
	set(value):
		elite = value
		if value:
			%enemy_type.material = load("res://Resources/Enemys/Rainbow.tres")
			scale = Vector2(2,2)
			speed = speed * 1.2
			
var type : Enemy:
	set(value):
		type = value
		%enemy_type.texture = value.texture
		damage = value.damage
		health = value.health * 3
	
func _physics_process(delta: float) -> void:
	check_separation(delta)
	knockback_update(delta)
	
# 超出屏幕时,释放对象
func check_separation(_delta)->void:
	separation = (player_reference.position - position).length()
	# 如果与玩家 位置相差过大,而且不是精英怪,则动删除该怪物
	if separation >= 800 and  not elite:
		queue_free()
	if separation < player_reference.nearest_enemy_distance:
		# 这里只需要设置对象,对象距离再player中设置
		player_reference.nearest_enemy = self
		
# 碰撞敌人时,击退敌人
func knockback_update(_delta) -> void:
	velocity = (player_reference.position - position).normalized() * speed
	knockback = knockback.move_toward(Vector2.ZERO,1)
	velocity += knockback
	var collider = move_and_collide(velocity * _delta)
	if collider:
		collider.get_collider().knockback  =  (collider.get_collider().global_position -  global_position).normalized() * 50

# 伤害弹窗
func damage_popup(amount:float)->void:
	# 实例化弹框
	var popup = damage_popup_node.instantiate()
	popup.text = str(amount)
	popup.position = position + Vector2(-50,-25)
	get_tree().current_scene.add_child(popup)

# 收到伤害
func take_damage(amount:float)->void:
	var tween = get_tree().create_tween()
	tween.tween_property(%enemy_type,"modulate",Color(3,0.25,0.25),0.2)
	tween.chain().tween_property(%enemy_type,"modulate",Color(1,1,1),0.2)
	# 将动画与自身绑定,这样当敌人消失时,动画会自动停止
	tween.bind_node(self)
	damage_popup(amount)
	health -= amount

# 随机掉落物
func drop_item()->void:
	# 检测怪物是否设置了掉落物
	if type.drops.size() == 0:
		return
	# 筛选随机的物品
	var item = type.drops.pick_random()
	# 实例化一个掉落物对象
	var item_to_drop = drop.instantiate()
	# 通过设置掉落物的类型,填充[pick_up]的具体属性
	item_to_drop.type = item
	# 设置掉落物的位置与怪物位置相同
	item_to_drop.position = position
	# 给掉落物设置用户信息
	item_to_drop.player_reference = player_reference
	# 将掉落物放入节点数
	#get_tree().current_scene.add_child(item_to_drop)
	#Can't change this state while flushing queries. Use call_deferred() or set_deferred() to change monitoring state instead.
	get_tree().current_scene.call_deferred("add_child", item_to_drop)
